﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using DomainModel;
using Services.Abstract;
using Group = DomainModel.Group;

namespace Web
{
    public partial class Register : BasePage
    {
        public IUserService UserService { get; set; }
        public IUserProfileService UserProfileService { get; set; }
        public IGroupService GroupService { get; set; }
        public IEmailService EmailService { get; set; }

        protected new void Page_Load(object sender, EventArgs e)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                Response.Redirect("/");
            }

            SetRequiredAttributes(new List<WebControl> { TbFio, TbLogin, TbPassword, TbEmail, });

            BindDdlGroups();
            BindDdlChilds();
        }

        private void BindDdlGroups()
        {
            DdlGroups.DataSource = GroupService.GetAll().OrderBy(g => g.Name);

            DdlGroups.DataValueField = "Id";
            DdlGroups.DataTextField = "Name";

            DdlGroups.DataBind();
        }

        private void BindDdlChilds()
        {
            var students = UserService.GetStudentsWithoutParent().OrderBy(s => s.UserProfile.Fio);

            var ds = new List<object>();

            foreach (var student in students)
            {
                ds.Add(new
                           {
                               student.Id,
                               student.UserProfile.Fio,
                           });
            }

            DdlChilds.DataSource = ds;

            DdlChilds.DataValueField = "Id";
            DdlChilds.DataTextField = "Fio";

            DdlChilds.DataBind();
        }

        private Role GetCheckedRadioRole()
        {
            if (RadioRoleStudent.Checked)
                return Role.Student;
            if (RadioRoleParent.Checked)
                return Role.Parent;
            if (RadioRoleTeacher.Checked)
                return Role.Teacher;
            if (RadioRoleTDW.Checked)
                return Role.TrainingDivisionWorker;

            return Role.None;
        }

        protected void BtnRegister_OnClick(object sender, EventArgs e)
        {
            string fio = TbFio.Text;
            string login = TbLogin.Text;
            string password = TbPassword.Text;
            string email = TbEmail.Text;
            Role role = GetCheckedRadioRole();

            User user = new User(login, email, role);
            user.SetPasswordHash(password);
            UserProfile profile = new UserProfile(fio) { User = user };
            user.UserProfile = profile;

            if (role == Role.Student)
            {
                long groupId;
                try
                {
                    groupId = long.Parse(DdlGroups.SelectedValue);
                }
                catch (FormatException)
                {
                    throw new Exception("Неверный идентификатор группы.");
                }

                Group group = GroupService.GetById(groupId);
                if (group == null)
                    throw new Exception("Ошибка базы данных. Невозможно найти группу.");

                user.Group = group;
            }
            else if (role == Role.Parent)
            {
                long childId;
                try
                {
                    childId = long.Parse(DdlChilds.SelectedValue);
                }
                catch (FormatException)
                {
                    throw new Exception("Неверный идентификатор ребенка.");
                }

                User child = UserService.GetById(childId);
                if (child == null)
                    throw new Exception("Ошибка базы данных. Невозможно найти ребенка.");

                user.Child = child;
            }

            try
            {
                UserProfileService.SaveOrUpdate(profile);
                UserService.SaveOrUpdate(user);

                string msgBody = "<h1>Уважаемый " + user.UserProfile.Fio + "</h1>" +
                    "Спасибо за регистрацию на ресурсе StudyControl.</br>" +
                    "Ваш логин: " + user.Login + "<br>" +
                    "После проверки администрацией, Вы сможете пользоваться ресурсом StudyControl.";

                EmailService.Send(user.Email, "Регистрация на ресурсе StudyControl", msgBody);

                Response.Redirect("/RegisterComplete.aspx");
            }
            catch (Exception ex)
            {
                ShowFormError(RegisterFormError.ClientID, ex.Message);
            }
        }
    }
}